package org.amuxia.emailtest.servlet;

import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.amuxia.emailtest.pojo.User;
import org.amuxia.emailtest.utils.EmailUtils;
import org.amuxia.emailtest.utils.MyJDBC;

/**
 * @author amuxia
 * 2017年7月24日
 */
@WebServlet("/RegistServlet")
public class RegistServlet extends HttpServlet {  
    private static final long serialVersionUID = 1L;  
  
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
        String username = request.getParameter("username");  
        String password = request.getParameter("password");  
        String email = request.getParameter("email"); 
        String codeUrl = UUID.randomUUID().toString();
        User user = new User(); 
        user.setUsername(username);  
        user.setPassword(password);  
        user.setEmail(email);  
        user.setActivated(false);  //刚注册默认是没有激活状态
        String SQL = "insert into tb_user(username,password,email,activated,codeUrl) value (?,?,?,?,?) ";
        MyJDBC.insert(SQL, false, username,password,email,0,codeUrl);//注册信息插入数据库
        String querySQL = "select * from tb_user where email=?";
        ResultSet rs = MyJDBC.query(querySQL, email);
        try {
			if(rs.next()){
				user.setId(rs.getInt(1));
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
        // 注册成功后,发送帐户激活链接  
        request.getSession().setAttribute("user", user); 
        EmailUtils.sendAccountActivateEmail(user); 
        request.getRequestDispatcher("/WEB-INF/jsp/success.jsp").forward(request,response);  
    }  

}
